//
//  LZVideoCellPresenterForGroupon.m
//  laziz_Consumer
//
//  Created by xbnzd on 17/4/19.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZVideoCellPresenterForGroupon.h"

#import "LZPromotionStatusModel.h"
#import "LZVideoListModel.h"
#import "LZUserModel.h"

#import "LZHomePageViewController.h"
#import "LAMerchantDetailTableView.h"
#import "LZFightGroupDetailPopView.h"
#import "LZGroupListViewController.h"
#import "LZStartGroupViewController.h"
#import "LZLoginViewController.h"
#import "LZVideoTableViewCell.h"
#import "LZAlertView.h"

#import "LZCheckCouponAndGrouponPresenter.h"
#import "LZGrouponPresenter.h"

#import "extobjc.h"

typedef NS_ENUM(NSInteger, ClickBtnState) {
    kBtnEvent_joinGroupon,
    kBtnEvent_startNewGroupon,
    kBtnEvent_none
};

@interface LZVideoCellPresenterForGroupon ()
@property (nonatomic, copy) NSString *selectedIndexPathIdentifier;

@property (nonatomic, weak) LZFightGroupDetailPopView *groupDetailPopView;

@property (nonatomic, strong)  LZPromotionStatusModel *statusModelTemp;

@property (nonatomic, assign) ClickBtnState btnEventCode; // 标记是点击了参加团购,还是创建新团
@end

@implementation LZVideoCellPresenterForGroupon

- (void)grouponDealClickCellButtonIndex:(VideoCellDelegateClickEventCode)index andCellIndexPath:(NSIndexPath *)cellIndexPath andNavigationController:(UINavigationController *)navigationController andHidesBottomBarWhenPushed:(BOOL)hidesBottomBarWhenPushed andCellModel:(id)model andOtherObject:(id)object andRefreshBlcok:(void (^)(VideoCellRefreshType, BOOL))refreshBlcok
{
    LZVideoListModel *videoModel = (LZVideoListModel*)model;
    
    //**********************************************************
    //*******************  想直接测试动画.解开下面的两句   ***********
    
//    [self openGrouponPopViewWithModel:videoModel nav:navigationController indexPath:cellIndexPath otherObject:object];
//    return;
    
    //******************  想直接测试动画.解开上面的两句   ************
    //*********************************************************
    
    
    //获取团购详情
    @weakify(self);
    
    if ([self checkLoginStateWithNavigationController:navigationController andHidesBottomBarWhenPushed:hidesBottomBarWhenPushed]) {
        
        self.selectedIndexPathIdentifier = [[NSString stringWithFormat:@"%ld_%ld_group",cellIndexPath.section,cellIndexPath.row] copy];
        
        // 如果已登录
        if (videoModel.isGroupon) {
            // 已参团
            [self showAlertView:LZLocalizedString(@"group_joined_remind", nil)];
            self.selectedIndexPathIdentifier = nil;
            return;
        }
        NSTimeInterval remainTimeInterval = videoModel.grouponEndTime/1000 - videoModel.currentTime/1000;
        if (remainTimeInterval <= 0) {
            // 倒计时结束
            [self showAlertView:LZLocalizedString(@"group_closed_remind", nil)];
            self.selectedIndexPathIdentifier = nil;
        }
        else {
            
            // LY ----- 加loading    2017/04/27
            __block BOOL isRequestFinshed = NO;
            LZBaseViewController *vc = navigationController.viewControllers.lastObject;

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (isRequestFinshed == NO) {
                    [vc stopLoadingViewForView:vc.tabBarController.view];
                    [vc startLoadingViewForView:vc.tabBarController.view loadingViewUserInteractionEnabled:YES];
                }
            });
            
            [LZCheckCouponAndGrouponPresenter checkGrouponWithPromotionId:videoModel.videoId ResultSuccess:^(id result) {
                isRequestFinshed = YES;
                [vc stopLoadingViewForView:vc.tabBarController.view];
                @strongify(self);
                DLog(@"%@",[NSString stringWithFormat:@"%ld_%ld_group",cellIndexPath.section,cellIndexPath.row]);
                if (self.selectedIndexPathIdentifier.length == 0 || ![self.selectedIndexPathIdentifier isEqualToString:[NSString stringWithFormat:@"%ld_%ld_group",cellIndexPath.section,cellIndexPath.row]]) {
                    return ;
                }
                
                self.selectedIndexPathIdentifier = nil;
                
                LZPromotionStatusModel *modelTemp = (LZPromotionStatusModel*)result;
                if (modelTemp.isPromotion) {
                    videoModel.isGroupon = YES;
                    // 已参团
                    [self showAlertView:LZLocalizedString(@"group_joined_remind", nil)];
                }
                else if (modelTemp.isExpired) {
                    // 已过期
                    [self showAlertView:LZLocalizedString(@"group_closed_remind", nil)];
                }
                else if (modelTemp.isOffLine) {
                    DLog(@"商家已下线");
                    [self showAlertView:LZLocalizedString(@"restaurant_offline_remind", nil)];
                }
                else {
                    [self openGrouponPopViewWithModel:videoModel nav:navigationController indexPath:cellIndexPath otherObject:object];
                }
            } ResultFailed:^(NSString *remind) {
                @strongify(self);
                self.selectedIndexPathIdentifier = nil;
                isRequestFinshed = YES;
                [vc stopLoadingViewForView:vc.tabBarController.view];
            }];
        }
    }

}

- (void)openGrouponPopViewWithModel:(LZVideoListModel *)videoModel nav:(UINavigationController *)navigationController indexPath:(NSIndexPath *)indexP otherObject:(id)object
{
    CGPoint p = [self getViewClickPointCoverInWindowWithIndexPath:indexP nav:navigationController];
    UIWindow *w = [UIApplication sharedApplication].keyWindow;
    
    
    LZFightGroupDetailPopView *vTemp = [[LZFightGroupDetailPopView alloc] init];
    _groupDetailPopView = vTemp;
    
    self.groupDetailPopView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [w addSubview:self.groupDetailPopView];
    self.groupDetailPopView.animationBeginPoint = p;
    self.groupDetailPopView.limitCountDownCalculator = object;
    [self.groupDetailPopView showSelfAnimation];
    
    self.statusModelTemp = nil;
    self.btnEventCode = kBtnEvent_none; //默认无操作
    //获取团购详情
    
    @weakify(self);
    [LZGrouponPresenter getGrabCouponOrFightGroupsDetailWithVideoID:videoModel.videoId ResultSuccess:^(LZGrabCouponAndFightGroupsDetialModel *model) {
       
        @strongify(self);
        self.groupDetailPopView.detailModel = model;
        
    } ResultFailed:^(NSString *remind) {
    
    }];
    
    
    //点击参团
    self.groupDetailPopView.joinGroupSuccessBlock = ^(){
        @strongify(self);
        [self.groupDetailPopView setUserInteractionEnabled:NO];
        [LZCheckCouponAndGrouponPresenter checkGrouponWithPromotionId:videoModel.videoId ResultSuccess:^(id result) {
            @strongify(self);
            self.statusModelTemp = (LZPromotionStatusModel*)result;
            self.btnEventCode = kBtnEvent_joinGroupon;
            
            if (self.statusModelTemp.isPromotion) {
                DLog(@"已参团");
                [self.groupDetailPopView cancelSelfAction];
            }
            else if (self.statusModelTemp.isExpired) {
                DLog(@"已过期");
                [self.groupDetailPopView cancelSelfAction];
            }
            else if (self.statusModelTemp.isOffLine) {
                DLog(@"商家已下线");
                [self.groupDetailPopView cancelSelfAction];
            }
            else {
                [self.groupDetailPopView cancelSelfAction];
            }
            [self.groupDetailPopView setUserInteractionEnabled:YES];
            
        } ResultFailed:^(NSString *remind) {
            @strongify(self);
            [self.groupDetailPopView setUserInteractionEnabled:YES];
        }];
    };
    
    //开启新团
    self.groupDetailPopView.startNewGroupBlock = ^(){
        @strongify(self);
        [self.groupDetailPopView setUserInteractionEnabled:NO];
        [LZCheckCouponAndGrouponPresenter checkGrouponWithPromotionId:videoModel.videoId ResultSuccess:^(id result) {
            @strongify(self);
            self.statusModelTemp = (LZPromotionStatusModel*)result;
            self.btnEventCode = kBtnEvent_startNewGroupon;
            
            if (self.statusModelTemp.isPromotion) {
                DLog(@"已参团");
                [self.groupDetailPopView cancelSelfAction];
            }
            else if (self.statusModelTemp.isExpired) {
                DLog(@"已过期");
                [self.groupDetailPopView cancelSelfAction];
            }
            else if (self.statusModelTemp.isOffLine) {
                DLog(@"商家已下线");
                [self.groupDetailPopView cancelSelfAction];
            }
            else {
                [self.groupDetailPopView cancelSelfAction];
            }
            [self.groupDetailPopView setUserInteractionEnabled:YES];
        } ResultFailed:^(NSString *remind) {
            @strongify(self);
            [self.groupDetailPopView setUserInteractionEnabled:YES];
        }];
        
    };
    
    self.groupDetailPopView.cancelSelfAcimationEndBlock = ^(){
        @strongify(self);
        if (self.statusModelTemp.isPromotion) {
            DLog(@"已参团");
            [self showAlertView:LZLocalizedString(@"group_joined_remind", nil)];
        }
        else if (self.statusModelTemp.isExpired) {
            DLog(@"已过期");
            [self showAlertView:LZLocalizedString(@"group_closed_remind", nil)];
        }
        else if (self.statusModelTemp.isOffLine) {
            DLog(@"商家已下线");
            [self showAlertView:LZLocalizedString(@"restaurant_offline_remind", nil)];
        }
        else {
            if (self.btnEventCode == kBtnEvent_startNewGroupon) {
                LZStartGroupViewController *vc = [[LZStartGroupViewController alloc] init];
                vc.rulesModel = self.groupDetailPopView.detailModel;
                vc.hidesBottomBarWhenPushed = YES;
                [navigationController pushViewController:vc animated:YES];
            }else if (self.btnEventCode == kBtnEvent_joinGroupon){
                LZGroupListViewController *vc = [[LZGroupListViewController alloc] init];
                vc.videoId = [videoModel.videoId copy];
                vc.hidesBottomBarWhenPushed = YES;
                [navigationController pushViewController:vc animated:YES];
            }
        }
    };
}

/**
 获取点击位置在widow的点
 
 @param indexP <#indexP description#>
 @param nav <#nav description#>
 @return <#return value description#>
 */
- (CGPoint)getViewClickPointCoverInWindowWithIndexPath:(NSIndexPath *)indexP nav:(UINavigationController *)nav
{
    id tab;
    CGPoint clickPoint = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    UIViewController *lastVC = nav.viewControllers.lastObject;
    
    if ([lastVC isKindOfClass:[LZHomePageViewController class]]) {
        for (UIView *sub in lastVC.view.subviews) {
            if ([sub isKindOfClass:[UITableView class]]) {
                tab = (UITableView *)sub;
            }
        }
    }else{
        for (UIView *sub in lastVC.view.subviews) {
            if ([sub isKindOfClass:[LAMerchantDetailTableView class]]){
                LAMerchantDetailTableView *tabTemp = (LAMerchantDetailTableView *)sub;
                tab = (LAMerchantDetailVideoTableView *)tabTemp.videoTable;
            }
        }
    }
    
    LZVideoTableViewCell *cc = [tab cellForRowAtIndexPath:indexP];
    extern NSInteger couponAndGrouponBgViewTag;
    extern NSInteger grouponBgViewTag;
    for (UIView *sub in cc.contentView.subviews) {
        if (sub.tag == couponAndGrouponBgViewTag) {
            for (UIView *grouponBgView in sub.subviews) {
                if (grouponBgView.tag == grouponBgViewTag) {
                    CGRect rectTemp = [grouponBgView convertRect:grouponBgView.frame toView:nil];
                    if (rectTemp.origin.x == 0) {
                        clickPoint = CGPointMake(rectTemp.origin.x + rectTemp.size.width/2, rectTemp.origin.y + rectTemp.size.height/2);
                    }else{
                       clickPoint = CGPointMake(rectTemp.origin.x - rectTemp.size.width/2, rectTemp.origin.y + rectTemp.size.height/2);
                    }
                }
            }
        }
    }
    
    return clickPoint;

}

- (BOOL)checkLoginStateWithNavigationController:(UINavigationController*)navigationController andHidesBottomBarWhenPushed:(BOOL)hidesBottomBarWhenPushed {
    if ([[LZUserModel Instance] isLogin]) {
        return YES;
    }
    else {
        // 如果未登录
        LZLoginViewController * vc = [[LZLoginViewController alloc] init];
        if (hidesBottomBarWhenPushed) {
            vc.hidesBottomBarWhenPushed = YES;
        }
        [navigationController pushViewController:vc animated:YES];
        
        return NO;
    }
}

#pragma mark - LZAlerView

- (void)showAlertView:(NSString*)message {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:message andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
}


@end
